<?php

namespace Yeevers\Api;

use GuzzleHttp\Client;
use Yeevers\Api\Util\AesUtils;
use Yeevers\Api\Util\HttpRequest;
use Yeevers\Api\Util\RSAUtils;

class YeeverseBaseClient
{

    public function __construct()
    {

    }

    /**
     * @param $YeeverseRequest YeeverseRequest
     * @return 基础请求方法
     */
    public static function
    baseRequest($url, $dataDict, $appId, $aesKey, $apiPrivateKey,$yeeversePublicKey)
    {


        $YeeverseRequest = new YeeverseRequest();
        $YeeverseRequest->appId = $appId;
        $YeeverseRequest->aesKey = $aesKey;
        $YeeverseRequest->httpMethod = "POST";

        if (empty($appId)) {
            error_log("appId 不能为空");
        }

        if (empty($aesKey)) {
            error_log("aesKey 不能为空");
        }


        $requestVo = new YeeverseRequestVO();

        $jsonStr = json_encode($dataDict);

        printf("json1=".$jsonStr);

        printf("\n");
        printf("aes=".YeeverseConfig::$aesKey."\n");
        printf("pk=".$yeeversePublicKey."\n");

        $headers = array();
        $headers['appid'] = $appId;
        $headers['sign'] = RSAUtils::Sign($jsonStr, $apiPrivateKey);
        $headers['aesKey'] = RSAUtils::encript(YeeverseConfig::$aesKey,$yeeversePublicKey);

        printf("aesKey=".$headers['aesKey']."\n");


        $requestVo->head = $headers;

        $body = AesUtils::encrypt($jsonStr,$aesKey);
        $requestVo->body = $body;

        printf("请求原文=".json_encode($requestVo)."\n");

        $YeeverseRequest->jsonParam = urlencode(json_encode($requestVo));


        $result=HttpRequest::curl_request($url,$YeeverseRequest);

        if(empty($result)){
            error_log("返回结果异常");
        }
        printf("map=".$result."\n");
        $resultVo=json_decode($result);
        var_dump($resultVo);

        $resultDict=array();

        if(!empty($resultVo->code)){
            printf("直接访问code模式=");
            $resultDict["code"]=$resultVo->code;
            $resultDict["message"]=$resultVo->message;
        }else{
            $aesKeyResp=$resultVo->head->aesKey;
            $bodyResp=$resultVo->body;
            $aesKeyResp=RSAUtils::decript($aesKeyResp,$apiPrivateKey);
            printf("返回aesKey=".$aesKeyResp."\n");
            $bodyRespStr=AesUtils::decrypt($bodyResp,$aesKeyResp);
            print_r("返回body="."$bodyRespStr"."\n");
            $resultDict=json_decode($bodyRespStr);
        }

        return $resultDict;
    }

    /**
     * 发起基础请求（版本4）
     *
     * @param string $url 请求的URL
     * @param array $dataMap 请求的数据，键值对数组
     * @return string JSON格式的响应数据
     */
    public function baseRequestV4($url, $dataMap = [])
    {
        // 检查配置项是否为空
        if (empty(trim(YeeverseConfig::$serverRoot))) {
            error_log("serverRoot is empty");
        }
        if (empty(trim(YeeverseConfig::$apiPrivateKey))) {
            error_log("apiPrivateKey is empty");
        }
        if (empty(trim(YeeverseConfig::$appId))) {
            error_log("appId is empty");
        }

        // 按照字母升序排序请求数据
        ksort($dataMap);

        // 将请求数据按照键值对拼接成字符串
        $signStr = implode("&", $dataMap);

        // 发起POST请求
        $response = (new Client())->post($url, [
            'headers' => [
                'Content-Type'           => "application/json",
                'x-yeeverse-appid'       => YeeverseConfig::$appId,
                'x-yeeverse-sdk-version' => 'v4',
                'x-yeeverse-sign'        => RSAUtils::signV4($signStr, YeeverseConfig::$apiPrivateKey)
            ],
            'body'    => json_encode($dataMap, JSON_UNESCAPED_UNICODE)
        ]);

        // 返回JSON格式的响应数据
        return $response->getBody()->getContents();
    }


}

